Central Article

Using Regular Expressions in Macromedia Central

Byron Saltysiak

Regular expressions are one of the most powerful new features built into Macromedia Central—so powerful that many people wish they were part of Macromedia Flash Player, and some people have even created them on occasion in custom classes. As text patterns, regular expressions can be searched for in strings of text and then be used in different ways to return a large variety of results.

Now that Macromedia has built them into Macromedia Central, and based them on Perl regular expression syntax and the ECMAScript 4 implementation, you have a standard way to utilize them.

This article covers regular expressions from the ground up. If you are already familiar with regular expressions and Perl syntax, skip straight to "Implementing Regular Expressions in Central" for Central-specific usage.

Regular Expressions Explained

Quite simply, regular expressions are text patterns. They are generally searched for in strings of text and can be used in different ways to return a large variety of results. A regular expression can be as simple as a string—for example, "hello". You could then search another large amount of text to see if this pattern exists. Regular expressions also possess powerful notations that allow you to specify any possible type of pattern, such as "a word starting with h and ending with o," "a word that is all lowercase," "a word containing double letters," or "a word containing five letters." Virtually any pattern is possible.

Regular expressions can help you greatly. Consider the task of parsing a URL with a query string—for example:

http://my.company.com/some/path.html?foo=$_hello&bar=world&test=test@test.com

Your task is to find the first variable whose corresponding value is a valid e-mail address.

Parsing this information using string functions would be painful and would probably require many commands and a loop, like so:

// string function version
var url = "http://my.company.com/some/path.html?foo=_hello&bar=world&test=test@test.com";
var varString = url.split("?")[1];
var pairs = varString.split("&");
var result = new Array();
for (each in pairs) {
   var tmp = pairs[each].split("=");
   var name = tmp[0];
   var value = tmp[1];
   if ((value.indexOf("@") > 0) &&
      (value.lastIndexOf(".") > value.indexOf("@")) && 
      (value.indexOf("@") == value.lastIndexOf("@"))) {
         // found one!
         result.push(name);
         result.push(value);
         break;
   }
}

Compare the previous code with a version using a regular expression. You're not necessarily going to be able to understand it yet, but you can notice the sizable difference:

// regular expression version
var url = "http://my.company.com/some/path.html?foo=$_hello&bar=world&test=test@test.com";
var re = new RegExp("(\\w+)=(\\w+@[\\w\\.]+)\\b");
var result = re.match(url);

Regular expressions may look confusing but they can do the job of many commands at once. In addition to matching and returning the matched portion(s) of interest, regular expressions can be used to test if a pattern exists and replace matched strings with another. I'll cover that later but first let's try to decipher some regular expression syntax.

Regular Expression Syntax

This section explains the special shorthand used to specify a text pattern with regular expressions. You will start by handling the simplest type of pattern and incrementally build upon it until you understand the most complicated patterns, including the one in the introductory example.

Simple Sequences

The simplest type of regular expression is called a "sequence" or simply a literal string pattern. The following code creates a regular expression called "re" with the literal pattern "hello". This is used on the next line to see if that pattern exists in the text we are testing—namely, the string "hello world":

var re = new RegExp("hello");
re.test("hello world"); // returns: true

We found the defined pattern, "hello", in the string "hello world". Note that the entire regular expression pattern has to be found, even though the pattern need not encompass the entire string. Also, the test() method returns the Boolean true to signify it was found. If you try the same pattern on different strings it may not be found:

var re = new RegExp("hello");
re.test("aabbcc");   // returns: false, "aabbcc" does not contain the pattern "hello"
// or 
re.test("Hello World");   // returns: false, regular expressions are case sensitive by default

Metacharacters

Characters that are used to help define a pattern, but are not searched for in their literal sense, are called metacharacters. One of the most common is the period (.), which matches any single character. Look how it is used in the following examples:

var re = new RegExp("h.llo");
re.test("hello");   // returns true, the '.' in the regular expression matched the 'e' in the string
re.test("h llo");   // returns true
re.test("hllo");   // returns false

Remember that metacharacters are not searched for literally. In the above example we aren't actually trying to match a period. But if you are, you must use another metacharater to escape the others—namely, the backslash (\). In Perl, you would then use "\." to get a literal "." character. However, due to the way that ActionScript handles backslashes you must escape it twice (\\). This double backslash must precede every metacharacter if you want to use it in its literal sense. For example:

var re = new RegExp("hello\\.");
re.test("hello.");   // returns true
re.test("hellox");   // returns false

Here are all the metacharacters you can use:

\ | ( ) [ { ^ $ * + ? .

Ranges

A pattern is not terribly interesting if you have to specify every character that you expect. Instead, with regular expressions you can specify a set of characters that you might expect, such as "any h or H," "any digit," "any uppercase letter," or "any whitespace character." These sets are referred to as ranges.

Using the previous example, to create a pattern that matches both "hello world" and "Hello World," let's define a range of characters we can expect using the special metacharacter "[":

var re = new RegExp("[Hh]ello");   // now we will look for either 'h' or 'H' followed by "ello"
re.test("hello world");   // returns: true
re.test("Hello world");   // returns: true
re.test("HELLO WORLD");   // returns: false
re.test("Hhello world");   // returns: ?

What do you think is returned in the last line? Does it return true? While the range is a set of more than one character, it still only matches one character at a time. In this example we are saying that we expect exactly one of either H or h. So will it fail to match and return false? Remember that the regular expression tries to match any part of the string, so in this case it finds a match starting with the second character in the string; that is, by skipping over the H and starting with the h. Here are some more examples:

var re = new RegExp("[Hh]ello");
re.test("asdfhelloasdfasdf");   // returns: true
re.test("hhhhHelloooooo");   // returns: true

Now you are equipped to define a range for, say, all lowercase letters—something like this: [abcdefghijklmnopqrstuvwxyz]. But this is pretty painful, so regular expressions are smart enough to allow you to specify a range using the "–" metacharacter like this: [a-z]. Here are some examples:

re1 = new RegExp("[abcdefghijklmnopqrstuvwxyz]ello");
re2 = new RegExp("[a-z]ello");   // equivalent to the above
re1.test("xello world");   // returns: true
re2.test("rello world");   // returns: true

Remember that regular expressions are case-sensitive; you need to define the uppercase range separately. Digit ranges can also be defined with "–":

re1 = new RegExp("[A-Z]ello");   // matches any uppercase alpha character and then "ello"
re2 = new RegExp("[0-9]");   // matches one of any digit
// ::tricky::
re3 = new RegExp("[A-Za-z]ello");   // matches any uppercase or lowercase alpha character and then "ello"

Many ranges are so commonly used that there is an even easier way to represent them. Common sets of characters are represented with special sequences, like the following: \\d \\s \\w. The \\d set matches any one digit, so \\d is equivalent to [0-9]. A backslashed letter is also used to define special single characters like a new line or tab. Table 1 lists these special character sets.

Table 1. Special Characters and Character Sets
Code Matches This
\\n New line
\\r Carriage return
\\t Tab
\\f Form feed
\\e Escape
\\d Digit equivalent to [0-9]
\\D Non-digit
\\w Word character (alphanumeric) equivalent to [a-zA-Z_0-9]
\\W Non-word character
\\s Whitespace character equivalent to [ \\t\\n\\r\\f]
\\S Non-whitespace character

Now you can use these special characters in your patterns. Here are some examples

re1 = new RegExp("hello\\sworld");
re2 = new RegExp("\\wello"); 
re1.test("hello world");   // returns true
re1.test("hello   world");   // returns true, note there is one tab in between words in this string
re2.test("Hello world");   // returns true
re2.test("+ello world");    // returns false, '+' is not a word character

Remember that unless you specify otherwise, a regular expression does not have to match the whole string. In order to match, however, some part of the string must match the whole regular expression.

Multipliers

With multipliers you no longer work only with a single character match in your regular expression. Instead, you can add the following type of specification to your patterns: "zero or more occurrences of...," "either zero or one occurrence of...," "between two and five occurrences of...," "at least one or more occurrences of...," etc.

Two common multipliers are "*" and "+". The * symbol means "zero or more instances of" and the + means "one or more instances of." Going back to the familiar example we could do the following:

re1 = new RegExp("hel+o");
re2 = new RegExp("hel*o");
re1.test("helllllllo world");   // returns true
re1.test("heo world");   // returns false
re2.test("heo world");   // returns true

You can now combine this with some of the other metacharacters to make more generic and powerful expressions:

re1 = new RegExp("h\\w+ w\\w+");   // match any two words, separated by a space, 
// in which the first starts with "h" and the second a "w", and each word
// must have at least one character other than the first
re1.test("howdy wally");   // returns true
re1.test("hello world");   // returns true
re1.test("won't match");   // returns false

Other notable multipliers include "?", which means "zero or one"; "{x}", which means you expect exactly x number of times; and "{x,y}", in which you specify integers x and y, and then a pattern must repeat at least x times but not more than y times. In the last example, if x is left out, the value defaults to 0; if y is left out, the value defaults to an open-ended "more". For instance:

re1 = new RegExp("h?el{2,}o w{1,2}orld");   // "hello world", but the 'h' is optional, there can be two or more 'l's 
// and either one or two 'w's
re1.test("ello world")   // returns true
re1.test("hellllo wworld");   // returns true
re1.test("helo world");   // returns false
re1.test("hello wwworld");   // returns false

Grouping

Now that you understand what multipliers are you may be wondering how to apply them to groups of characters. To do this you need the "( )" grouping metacharacters. By putting a portion of a regular expression inside parentheses you can apply multipliers to that entire portion.

The following examples illustrate the use of grouping. What we're trying to do is match the laughing sounds "hohoho," "hehehe," or "hahaha." Note the difference in the regular expressions and results:

re1 = new RegExp("h[aeo]{3}");   
re1.test("hahaha");   // returns false
re1.test("haaa");   // returns true
// instead we should group the 'h' and the following vowel
re2 = new RegExp("(h[aeo]){3}");
re2.test("hahaha");   // returns true
re2.test("haaa");   // returns false

This isn't exactly what we want, however, because the following also matches:

re2.test("hahohe");   // returns true

What we want is some way to say "make sure this part of the pattern looks like this other part." Thankfully, we can use the "memory" capabilities of regular expressions. Memory is also tied to the "( )" metacharacters; when you use them you create a memory holder in the regular expression that you can reference later using "\\" followed by a number. This number is the order in which the "(" appears left to right. That is, the first grouping is referenced by \\1 and, if there is a second one, it will be referenced by \\2. For example:

re1 = new RegExp("(h[aeo])\\1{2}");   // here the \1 refers to whatever was found in the first grouping
// and the {2} multiplies the \1 meta character.
// Now:
re1.test("hohoho");   // returns true
re1.test("hahohe");   // returns false
re2 = new RegExp("he(\\w)\\1o world(\\W)\\2");   // note the use of the \w and \W as well as memory 
// and the need to double the backslash '\\'
re2.test("hello world!!");   // returns true
re2.test("hemmo world??");   // returns true

In the second example we used grouping to allow memory usage, although the created group only had one character in it. Memory has other powerful implications that I will go into more deeply when I discuss the RegExp.prototype.match() command.

Anchors

A very useful bit of syntax, anchors are characteristics of a string that are not actual characters but, instead, occur between characters. There are two important types of anchors. The first are string boundary anchors: The beginning of the string matches "^" and the end of the string matches "$":

re1 = new RegExp("he");
re2 = new RegExp("^he");
re1.test("the quick brown fox...");   // matches in the word "the"
re2.test("the quick brown fox...");   // does not match because the "he" is not at the beginning of the string

The second type of anchors are word boundary anchors, where the boundary of a word matches the character "\\b". What I mean by word boundary is the place between a \\w and a \\W character or a string boundary. This is not the same as a \\s character, which matches whitespace. Anchors do not match characters; they match what occurs between characters, such as the ending of a word or the beginning of a line (see Table 2). Similarly, \\B matches a non-word boundary. Here are some examples:

re3 = new RegExp("cart\\b");    // Matches the string "cart" followed by a word boundary, since 't' is a word character, then searches for a non-word character next to it. 
re4 = new RegExp("cart\\B");   // Searches for "cart" that is not followed by a word boundary.

So the next character has to be a word character too.

re3.test("cart before the horse");   // returns true
re3.test("cartwheel before the horse");   // returns false
re4.test("cart before the horse");   // returns false
re4.test("cartwheel before the horse");   // returns true
Table 2. Important Anchors
Anchor Meaning
^ Beginning of the line
$ End of the line
\\b Word boundary
\\B Not a word boundary

Besides the regular expression syntax I've covered so far, you can use the alternation "|" which allows you to use Boolean OR in your patterns. There are additional grouping methods, such as "(?: )", and flags that you can set. Table 3 recaps what I've covered. For the full documentation on Perl regular expression syntax, which Macromedia Central uses, read the Perl 5.8.0 Documentation page about perlre (Perl regular expressions).

Table 3. Metacharacters
Character Function
\ Escape character (generally needs to be doubled in ActionScript)
() Groups characters; also used for memory
[] Defines a range of characters
{} Multiplier: defines an explicit number of characters to match
^ Anchor: matches beginning of string
$ Anchor: matches end of string
* Multiplier: makes preceding character match zero or more times
+ Multiplier: makes preceding character match one or more times
? Multiplier: makes preceding character match zero or one time
. Matches any character
| Alternation: represents Boolean OR
(?:) Groups without creating memory

Implementing Regular Expressions in Central

The implementation of regular expressions in Macromedia Central follows the ECMA-262 Standard of the ECMAScript Language Specification. The two ways in which you use regular expressions is through the new RegExp class or through an added method to the String class. In the following sections I walk you through what you need to know about both.

RegExp Object

You may have noticed the RegExp constructor used in the previous code samples. It creates a RegExp object that accepts a string, which you use to define the pattern of the expression, and a second optional parameter in which you can easily set properties for the resulting RegExp object. Here are some examples:

re1 = new RegExp("(\\w)\\1");   // regular expression that matches any two consecutive "word" characters
re2 = new RegExp("hello world", "i");   // matches the string "hello world" and is case-insensitive due to the 'i' flag (explained below)

RegExp Properties

Among the handful of properties of the RegExp object are several Boolean properties that allow you to alter the default behavior. The default value for all flags is false (see Table 4).

Table 4. Constructor Flags and Their Property Names
Flag Name
i ignoreCase
s dotall
m multiline
x extended
g global

Note: All the Boolean properties in Table 4 are read-only and default to false. They can only be set to true by passing the corresponding flag into the second parameter of the constructor.

The ignoreCase property is perhaps the easiest to understand. By adding an "i" to the second parameter when you construct a RegExp object, the ignoreCase property is set to true. With this property set, a character literal now matches either upper- or lowercase words. Here is an example of its usage:

re = new RegExp("hello world", "i");
trace(re.ignoreCase);   // outputs true
re.test("Hello World");   // returns true
re.test("hello world");   // returns true
re.test("HELLO WORLD");   // returns true

The dotall property is also relatively easy to understand. The default behavior of the RegExp object is for the dot (.) metacharacter to not match a newline character (\n). When the dotall property is set to true, using the "s" flag, the dot matches the newline character:

var testString = "hello blah\nblah world"; 
var re = new RegExp("hello.*world"); 
trace(re.dotall);   // outputs false
re.test(testString);   // returns false, the . does not match the \n

var re2 = new RegExp("hello.*world ", "s"); 
trace(re2.dotall); // outputs true
re2.test(testString); // returns true

If you want to set two Boolean properties to true, pass both flags into the second parameter of the RegExp constructor:

var re = new RegExp("hello", "si");   // order of flags does not matter
trace(re.ignoreCase);   // outputs true
trace(re.dotall);   // outputs true

The multiline property is interesting in that it changes the meaning of the ^ and $ anchors. When multiline=false, the ^ matches the beginning of the entire string and the $ matches the end of the entire string. However, when multiline=true, each line within the string has its own line-end anchors. When a RegExp object has this setting, ^ matches the beginning of the entire string or the beginning of a new line (after a \n character). Similarly, $ matches the end of the entire string or the end of a line (before a \n character). For example:

Var testString = "hello\nworld";
Var re1 = new RegExp("^hello$");
Var re2 = new RegExp("^hello$", "m");

Re1.test(testString);   // returns false; the $ is not matched because the end of the string is not reached
Re2.test(testString);   // returns true; the $ is matched because the end of a line is reached

The extended property simply ignores any whitespace within the first parameter to the RegExp constructor. To include whitespace in the regular expression when using the extended property, use a whitespace metacharacter such as \\s:

var re1 = new RegExp("hello world", "x");
var re2 = new RegExp("hello\\sworld", "x");
re1.test("hello world");   // returns false because the space in the constructor string was ignored
re1.test("helloworld");   // returns true
re2.test("hello world");   // return true; used the whitespace metacharacter \\s for the space

The related global and lastIndex properties are probably the most difficult to grasp. When the global property is set to true, method calls on a RegExp object pick up where the prior call left off. This is done by starting the search at one plus the index that was found in the previous search. To do this, the lastIndex property is used. Whenever a RegExp method is called, the index of the last character of the string that is matched plus one is stored in the lastIndex property. If no match is found, or if the global property is false, then lastIndex is set to zero.

Here are some examples to illustrate these properties:

var testString = "hello hello";
re = new RegExp("hello", "g");
trace(re.global);   // outputs true
trace(re.lastIndex);   // outputs 0
re.test(testString);   // returns true; starting at 0 this method finds a match on the characters between indexes 0 and 4
trace(re.lastIndex);   // outputs 5; the last index matched was 4 (remember we count from 0) and then we add one
// since global was set to true the next time we call a method with this RegExp it starts from the index stored in the lastIndex property
re.test(testString);   // returns true; starts looking at 5 and finds a match between index 6 and 10
trace(re.lastIndex);   // outputs 11 
re.test(testString);   // returns false; there are no more matches in the string after the 11th character
trace(re.lastIndex);   // outputs 0; because no match was found, the lastIndex property is reset to 0

In addition to lastIndex, there is another non-Boolean property of a RegExp object, called source. This property holds the value of the first parameter used when constructing the RegExp. A possible use for this property would be to compare RegExp objects for equality:

var re = new RegExp("hi");
trace(re.source);   // outputs "hi"

RegExp Methods

The most basic method of a RegExp object is match(), which accepts a string as input and returns the portion of the string that was matched by the regular expression if a match exists and returns null if none exists. For example:

var re = new RegExp("\\bh\\w+\\b");
re.match("hello world");   // returns "hello"
re.match("my name is haldir");   // returns "haldir"
re.match("this won't match?");   // returns null

I have used the test() command throughout this article. It is simply a wrapper around the match() command: If match() returns null, then test() returns false; otherwise test() returns true. Using the examples above, we now have the following expressions:

var re = new RegExp("\\bh\\w+\\b");
re.test("hello world");   // returns true
re.test("my name is haldir");   // returns true
re.test("this won't match?");   // returns false

I previously mentioned the memory syntax using the "( )" metacharacters. These now play a new role with the match() command. The match() command actually returns an array of values but this array generally only has one element that is treated as a string. However, if you use the memory metacharacters, you can pass additional values out of the match() command. Let's say you want to match the pattern "My name is {someName}" but all you really care about is the name. In this case you can use the memory to return the name in a separate array element. For example:

var re = new RegExp("My name is \\b(\\w+)\\b");
re.match("His name is Tom and My name is Byron");   // returns "My name is Byron", "Byron"

The first element in the returned array is the whole string that is matched; the subsequent elements are the ordered memory groups, starting with their appearance from left to right. Another useful method for using regular expressions is to find some portion of text that matches a pattern and then replace it with another string. The RegExp.prototype.replace() method allows you to do this. It accepts two parameters: the string to search through and the replacement string. A new string with the replacements made is then returned:

// curse word filter 
var text = "hello there, I hope that you all are doing well";
var re = new RegExp("\\b\\w{4}\\b");
re.replace(text, "****");   // outputs "hello there, I **** **** you all are doing ****"

String Method

A new method has been added to the String object to make it more convenient to implement regular expressions. The String object now features the replace() command, which is a wrapper around the replace() method. The only difference is that the first parameter for this replace() method is a source string to define a regular expression, the same as you would use in the RegExp constructor:

// curse word filter using String.replace()
var text = "hello there, I hope that you all are doing well";
text.replace("\\b\\w{4}\\b", "****");   // replace all four-letter words with ****

Testing Tips

Because JavaScript follows the same ECMAScript standard as Macromedia Central, I find that an easy way to write and test regular expressions for Central is in an HTML file. The main difference I've found between these two implementations is that JavaScript uses exec(), whereas Central uses match(). The good news is that Central also allows exec(), which does the same thing as match(). However, there are other differences: the JavaScript implementation has more String methods that use regular expressions, and the Central implementation has a few more properties to set. Because you are not guaranteed that what works in JavaScript works in Central, it's a good idea to test all scripts in Central as a final step if you wrote them in JavaScript.

Here is an easy example of the contents of an HTML file I created to test one of the previous samples:

<script>
var re = new RegExp("\\bh\\w+\\b");

// note using 'exec()' in place of 'match()'
document.writeln(re.exec("hello world") + "<br>");   // displays "hello"
document.writeln(re.exec("my name is haldir") + "<br>");   // displays "haldir"
document.writeln(re.exec("this won't match?") + "<br>");   // displays null


document.writeln(re.test("hello world") + "<br>");   // displays "hello"
document.writeln(re.test("my name is haldir") + "<br>");   // displays "haldir"
document.writeln(re.test("this won't match?") + "<br>");   // displays null
</script>

To test this in Central, I simply create a text box and send output to it. Alternately, you could use trace(); just remember to set debug.enabled = true. Regular expressions only work in Central, not Flash, so your apps need to be running in the Central framework in order for these new APIs to work.

Useful Examples

One area in which regular expressions are extremely useful is form validation. Below is a list a regular expressions that you can use for validating. Although the names should be descriptive enough to determine their purpose, after reading and understanding this article you should have the necessary skills to read the regular expression syntax in Listing 1 and see exactly what each one does.

Listing 1. Useful Regular Expressions

// matches alphanumeric strings with at least one character 
var reWordPattern = new RegExp("^\\w+$");   

// matches all letter strings with at least one character 
var reLettersPattern = new RegExp("^[A-Za-z]+$");   

// matches all digit strings with at least one character 
var reDigitPattern = new RegExp("^\\d+$");   

// matches exactly two uppercase letters 
var reStatePattern = new RegExp("^[A-Z]{2}$");   

// matches exactly five digits or five digits plus '-' plus four digits 
var reZipPattern = new RegExp("^(?:\\d{5}|\\d{5}-\\d{4})$");  
  
// matches either xxx-xxx-xxxx or (xxx)xxx-xxxx 
var rePhonePattern = new RegExp("^(?:\\d{3}-\\d{3}-\\d{4}|\\(\\d{3}\\)\\s?\\d{3}-\\d{4})$"); 

// matches format mm/dd/yyyy with one-digit month or day possible and two-digit year possible 
var reDatePattern = new RegExp("^(\\d{1,2})/(\\d{1,2})/(\\d{2}|\\d{4})$"); 

// matches at least one character (and then possible '.' which must be followed by at least one more 
// character), then a '@', and then at least two alphanumeric words separated by a '.' but possibly more

var reEmailPattern = new RegExp("^(\\w(?:\\w|\\.\\w)*)@(\\w+\\.\\w(?:\\w|\\.\\w)*)$"); 

// matches the a valid url string; note that we're capturing the domain in memory (discussed later) 
var reUrlPattern = new RegExp("^(http|ftp|https|file)://(.*?)/.*$"); 
  

Note: Two metacharacters I use in Listing 1 but did not really discuss earlier are "|", which is read as "or", and "(?:", which works exactly the same as "(" except that no memory is stored when a group is made this way. If any of the following lines are unintelligible, look over the part of this article that corresponds to the symbols you see or review the Perl documentation on regular expression syntax.

You could use these regular expressions in the following ways for validation using the RegExp test() method:

function validate (form_mc) {
   var userName = form_mc.userName_txt.text;   // user name that was input
   var zipCode = form_mc.zipCode_txt.text;   // zip code that was input
   var phone = form_mc.phone_txt.text;   // phone number

   return (reWordPattern.test(userName) && reZipPattern.test(zipCode) && rePhonePattern.test(phone));
}

I designed the reDatePattern, reEmailPattern, and reUrlPattern examples in Listing 1 to have some useful memory in them. The other examples in Listing 1 do not have very interesting parts. Here's what I mean. A date has interesting parts—month, day, year—that could be used separately from the whole date. Likewise, an e-mail address has a username and domain name. But a word, number, or phone number doesn't really contain any parts of interest. A possible exception would be the area code from a phone number. Converting rePhonePattern to remember the area code is left as an exercise for you to tackle.

When reDatePattern.match() succeeds it returns an array with four elements. The first element is (as always) the entire portion of the string matched. The second, third, and fourth elements are defined using the "( )" memory metacharacters to be the month, day, and year, respectively. Meanwhile, reEmailPattern.match() returns three elements: The first is the whole match, the second is the user_name (portion before the "@"), and the third is the domain name (portion after the "@"). Finally, reUrlPattern.match() returns three elements: The first is the entire string matched, the second is the protocol used, and the third is the domain. Here are some examples of their usage:

if (reDatePattern.test(aDate)) {
   // passed so let's grab the results
   var results = reDatePattern.match(aDate);
   // note: since this pattern matches the whole string aDate == results[0]
   var month = results[1];
   var day = results[2];
   var year = results[3];
}
if (reEmailPattern.test(anEmailAddr)) {
   // passed so let's grab the results
   var results = reEmailPattern.match(anEmailAddr);
   var name = results[1];
   var domain = results[2];
}
if (reUrlPattern.test(myUrl)) {
   // passed so let's grab the results
   var results = reUrlPattern.match(myUrl);
   var protocol = results[1];
   var domain = results[2];
}

Resources

I hope this article helps give you both a better understanding of regular expressions and their syntax as well the necessary information you need to implement them within Macromedia Central. Although I tried to cover the most important pieces of syntax and ways in which you might use regular expressions, there are many aspects of regular expressions that I could not cover here.

My advice is to acquire a solid understanding of everything in this article first, because that will get you most of the way on any project. Then look to the Central documentation, the Perl documentation, and the ECMAScript documentation for more specifics (see below). If you start to feel that a regular expression is becoming too complicated or too difficult to work with, start searching the docs and the web to find an easier way. Most likely there is one. Good luck!

Perl

Perl 5.8.0 Documentation: perlre (Perl regular expressions)
www.perldoc.com/perl5.8.0/pod/perlre.html

ECMAScript

ECMAScript Language Specification (Standard ECMA-262) (PDF format, 184K)
www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf

ECMAScript Language Specification (HTML version)
www.el-mundo.es/internet/ecmascript.html

Macromedia Central

Developing_Applications.pdf (delivered with the Central Software Development Kit)
www.macromedia.com/devnet/central/sdk/

Macromedia Central Product Site
www.macromedia.com/go/central/

Macromedia Central Developer Center
www.macromedia.com/devnet/central/

Central MX: A central place for the Central community (blog by David Bisset)
www.centralmx.com

RegExp Builder, a Central application to help create RegExp code (by Byron Saltysiak)
www.saltysiak.com/byron/regexp/installer.html

Regular Expressions

Regular Expression Library
www.regxlib.com

"Five Habits for Successful Regular Expressions" by Tony Stubblebine, author of Regular Expression Pocket Reference (O'Reilly & Associates, 2003)
www.onlamp.com/pub/a/onlamp/2003/08/21/regexp.html

Regular-Expressions.info: "The Premier Web Site About Regular Expressions"
www.regular-expressions.info


About the author

Byron Saltysiak works for Turner Entertainment Group, where he's built websites, content management systems, web applications, and interactive TV applications since 2000. A member of Team Macromedia, Byron is a software developer who uses Java and Vignette, as well as Macromedia Central and Flash. He likes using Flash because of its power as an intelligent client. You can reach him at byron@saltysiak.com.